<template>
  <div class="container">
    <div class="btn" @click="toTop">顶部</div>
  </div>
</template>

<script>
import { set } from 'vue'
export default {
  data() {
    return {}
  },
  mounted() {
    //监听页面滚动
    window.addEventListener('scroll', this.scrollEvent) // 监听页面滚动
  },
  methods: {
    //页面滚动事件
    scrollEvent(e) {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      console.log(scrollTop)
    },
    // 平滑滚动到顶部
    toTop() {
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      let step = 50

      // 实现滚动效果
      const timer = setInterval(() => {
        scrollTop -= step
        document.body.scrollTop = scrollTop
        document.documentElement.scrollTop = scrollTop

        if (scrollTop <= 0) {
          clearInterval(timer)
        }
      }, 10)
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 500vh;
  width: 100%;
  background-image: linear-gradient(
    180deg,
    #7ccff1 5%,
    #4196ea 25%,
    #1d88fa 50%,
    #0a8233 100%
  );
  overflow-y: scroll;
  .btn {
    position: fixed;
    right: 10px;
    bottom: 100px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    font-size: 0.15rem;
    background-color: #fff;
    text-align: center;
    line-height: 50px;
  }
}
</style>
